$(document).ready(function() {

	var score = 0;
	var questions = 0;
	// var list = new Array;
	var list = new LinkedList();

	// list.insert('tom');
	// list.insert('harry');
	// list.insert('paul');
	// list.insert('tori');
	// list.insert('susie');   

	// console.log('After adding 5 elements ');
	// list.showAllElements();                         

	// console.log('size test');
	// console.warn(list.size());

	// list.remove('tori');            
	// console.log('After removing tori from the list ');  
	// list.showAllElements();         

	// list.insertItemNthPositionFromHead(3, 'bunty');         
	// console.log('After adding bunty at position 3 ');     
	// list.showAllElements();

	function calculate_pokemons(gen) {
		if (gen == "all")
			return ([0,20]);
			// return ([0, 649]);
		if (gen == "1g")
			return([0, 151]);
		if (gen == "2g")
			return([151, 251]);
		if (gen == "3g")
			return([251, 386]);
		if (gen == "4g")
			return([386, 493]);
		if (gen == "5g")
			return([493, 649]);
	};

	var json = $.getJSON('pokemon.json', function(pk) {

		var html_whoisit = '<p class="selectioned"></p>\
						<ul>\
							<li class="option ans1"></li>\
							<li class="option ans2"></li>\
							<li class="option ans3"></li>\
							<li class="option ans4"></li>\
						</ul>\
						<p class="timeout"></p>';

		var html_answer = '<h3></h3>\
						<p class="selectioned"></p>\
						<p class="info"></p>\
						<p class="next"><span>Suivant</span></p>';

		var html_end = '<p class="mode"><p>\
						<p class="result"></p>\
						<p class="desc"></p>\
						<p class="artwork"></p>\
						<p class="next again"><span>Recommencer</span></p>'

		var html_limit = '<input type="text" name="questions" id="questions" size="2" value="20" maxlength="4">\
							<label for="questions" class="question"> questions</label>'

		if ($('article input[id="limit"]:checked').attr("id") == "limit")
			$('article li .limit').empty().append(html_limit);

		$('article .modes input').click(function() {
			$(this).attr('id') != "limit" ? $(this).parent().find('.limit').empty() : $(this).parent().find('.limit').empty().append(html_limit);
		})

		$('article input.take-the-test').click(function() {
			var global_seconds = $('article input[name="seconds"]').attr('value');
			var global_lang = $('article input[name="lang"]:checked').attr('id');
			var global_mode = $('article input[name="mode"]:checked').attr('id');
			var global_number = (global_mode == "limit" ? $('article input[name="questions"]').attr('value') : null);
			var global_gen = $('article input[name="gen"]:checked').attr('id');
			var global_limits = calculate_pokemons(global_gen);
			if (global_seconds > 0 && (global_number > 0 || global_number == null))
				main_test(global_seconds, global_lang, global_limits[0], global_limits[1], global_mode, global_number, global_gen);
			global_seconds <= 0 ? $('article .seconds').addClass('fail') : $('article .seconds').removeClass('fail');
			global_number <= 0 ? $('article .question').addClass('fail') : $('article .question').removeClass('fail');
		});

		function main_test(a, lang, l1, l2, m, n, g) {
			var selectioned = '';
			var seconds = a;
			questions++;
			$('article .wrapper').empty().append(html_whoisit);
			$('article .wrapper').addClass('game');
			$('article .timeout').append(seconds + ' secondes restantes');
			generate_random();
			// console.warn(selectioned);
			$('article .selectioned').append('<img src="img/' + pk.mn[selectioned].num + '.png" alt="mystery"/>');
			list_options(pk, selectioned, lang);
			check_answer();
			var clock = setInterval(function() {
				seconds--;
				$('article .timeout').empty().append(seconds + ' secondes restantes');
				seconds == 0 ? answer('fail', true) : '';
			}, 1000);

			// function generate_random() {
			// 	selectioned = Math.floor((Math.random()*(l2-l1))+l1);
			// 	console.warn(">> " + selectioned);
			// 	console.warn(list);
			// 	if (!list[0])
			// 		list[0] = selectioned;
			// 	else {
			// 		var i = 0;
			// 		for (i in list) {
			// 			if (list[i] == selectioned) {
			// 				console.warn("recursive");
			// 				generate_random();
			// 			}
			// 		};
			// 		++i;
			// 		list[i] = selectioned;
			// 	}
			// }
			
			function generate_random() {
				selectioned = Math.floor((Math.random()*(l2-l1))+l1);
				console.warn(">> " + selectioned);
				if (list.matchElement(selectioned))
					generate_random();
				else
					list.insert(selectioned);
				list.showAllElements();
				console.log('DOUBLE?');
			}

			function check_answer() {
				$('article .option').click(function() {
					$(this).attr('value') == selectioned ? answer('right') : answer('fail');
				});
			};

			function answer(token, timeout) {
				clearInterval(clock);
				$('article .wrapper').empty().append(html_answer);
				token == 'fail' ? $('article h3').addClass('fail') : score++;
				$('article h3').append((token == 'right' ? 'Tu as raison !' : 'C\'est faux...'));
				timeout == true ? $('article h3').empty().append('Temps écoulé !') : '';
				$('article .selectioned').append('<img src="img/' + pk.mn[selectioned].num + '.png" alt="mystery"/>');
				$('article .info').append('Ce Pokémon s\'appelle <strong>' + pk.mn[selectioned][lang] + '</strong> !');
				$('article').find('.score').remove();
				if (m == "infini")
					$('article').prepend('<span class="score">' + Math.floor(score / questions * 100) + '%</span>');
				else if (m == "hardcore")
					$('article').prepend('<span class="score">Score : ' + score + '</span>');
				else if (m == "limit")
					$('article').prepend('<span class="score">' + score + '/' + n + '</span>');
				$('article .next span').click(function() {
					((m == "limit" && questions == n) || (m == "hardcore" && token == "fail")) ? end() : main_test(a, lang, l1, l2, m, n, g);
				});
			};

			function end() {
				$('article .score').remove();
				$('article .wrapper').empty().append(html_end);
				$('article .wrapper .mode').append('Mode ' + (m == "limit" ? 'limité' : 'hardcore') + ' sur ' +
													(g == "all" ? 'toutes les générations' : 'la génération '+ g.split('g')[0]));
				m == "limit" ? $('article .wrapper .result').append('Score : <strong>' + score + '/' + n + '</strong>') : '';
				m == "hardcore" ? $('article .wrapper .result').append('Score : <strong>' + score + '</strong>') : '';
				console.warn(score / questions)
				if (score / questions < 0.34)
					$('article .wrapper .artwork').append('<img src="5.png" alt="artwork" />');
				$('article .next span').click(function() {
					questions = 0;
					score = 0;
					main_test(a, lang, l1, l2, m, n, g);
				});				
			}

			function list_options(pk, selectioned) {
				var nb = new Array();
				for (i = 0; i < 4; i++)
					nb[i] = Math.floor((Math.random()*(l2-l1))+l1);
				real = Math.floor((Math.random()*4)+1);
				nb[real - 1] = selectioned
				if (!(nb[0] != nb[1] && nb[0] != nb[2] && nb[0] != nb[3] && nb[1] != nb[2] && nb[1] != nb[3] && nb[2] != nb[3]))
					list_options(pk, selectioned);
				else {
					for (i = 0; i < 4; i++)
						$('article .option.ans'+(i+1)).empty().append(pk.mn[nb[i]][lang]).attr("value", nb[i]);
				}
			};
		};
	})
	.error(function() {
		$('.goforit').empty().append('Erreur lors du chargement JSON !');
		$('.goforit').addClass('fail');
	});
});